<template>
	<view @click="isMore = false">
		<view class="statusbar"></view>
		<view class="goods-head" :style="'background:rgba(255,255,255,' + PageScrollTop / 100 + ')'">
			<!-- 返回 -->
			<view class="back" @click="onBack" v-if="!types==1">
				<view class="back-one" :class="{ action: PageScrollTop > 120 }">
					<text></text>
				</view>
			</view>
			<!-- tab切换 -->
			<view class="head-tab" v-if="PageScrollTop > 120">
				<view class="tab" :class="{'action':TabShow===0}" @click="onTab(0)">
					<text>商品</text>
					<text class="line"></text>
				</view>
				<view class="tab" :class="{'action':TabShow===1}" @click="onTab(1)">
					<text>评价</text>
					<text class="line"></text>
				</view>
				<view class="tab" :class="{'action':TabShow===2}" @click="onTab(2)">
					<text>详情</text>
					<text class="line"></text>
				</view>
			</view>
			<!-- 分享更多 -->
			
		</view>
		<!-- banner，标题 -->
		<view class="banner-title">
			<!-- banner -->
			<view class="banner">
				<swiper class="screen-swiper round-dot" indicator-dots="true" circular="true" autoplay="true"
					interval="5000" duration="500">
					<swiper-item v-for="(item, index) in banner" :key="index">
						<image :src="item" mode="aspectFill"></image>
						<!-- <video src="{{item.url}}" autoplay loop muted show-play-btn="{{false}}" controls="{{false
	        }}" objectFit="cover" wx:if="{{item.type == 'video'}}"></video> -->
					</swiper-item>
				</swiper>
			</view>
			<!-- 价格 -->
			<view class="price-info">
				<view class="price" style="align-items: baseline;" v-if="dataInfo.goods_type!=3&&dataInfo.goods_type!=4">
					<text class="min">￥</text>
					<text class="max">{{dataInfo.price_selling}}
					<text style="color: #f20;" v-if="dataInfo.balance2!=0">+{{dataInfo.balance2}}<text style="font-size: 24rpx;">礼品卡</text></text>
					</text>
					<view class="" style="margin-left: 10rpx;color: #999;text-decoration: line-through;">{{dataInfo.price_market}}</view>
				</view>
				<view class="price" v-if="dataInfo.goods_type==3">
					<text class="max">{{dataInfo.price_selling}}</text><text style="color: #f20;margin-left: 10rpx;font-weight: 700;">{{dataInfo.entrance_id==3?'优惠券':'礼品卡'}}</text>
				</view>
				<view class="price" v-if="dataInfo.goods_type==4">
					<text class="max" v-if="dataInfo.price_selling!=0">{{dataInfo.price_selling}}+</text><text class="max">{{dataInfo.balance3}}</text><text style="color: #f20;margin-left: 10rpx;font-weight: 700;">红包券</text>
				</view>
				
				<view class="info">
					<view class="list" @click="onAttention">
						<text class="iconfont"
							:class="AttentionShow===1?'icon-guanzhu-on action':'icon-guanzhu-off'"></text>
						<text>{{ AttentionShow === 1 ? '已关注' : '关注' }}</text>
					</view>
				</view>
			</view>
			<!-- 限时抢购 -->
			
			<!-- 标题 -->
			<view class="goods-title">
				<text>{{dataInfo.name}}</text>
			</view>
			<view class="miaoshu" style="padding-left: 30rpx;color: #999;">
				{{dataInfo.remark}}
			</view>
			<!-- 开通会员 -->
		</view>
	
		<!-- 属性规格 -->
		<!-- <view class="goods-discounts">
			<view class="list" @click="getShow(1)">
				<view class="title">已选</view>
				<view class="content">
					<text>{{shop_key}}</text>
				</view>
				<view class="more">
					<text class="iconfont icon-more"></text>
				</view>
			</view>
			<view class="list">
				<view class="title">运费</view>
				<view class="content">
					<text>免运费</text>
				</view>
			</view>
		</view> -->
		<!-- 评价 -->
		
		
		<!-- 商品介绍 -->
		<view class="products-introduction" ref="products">
			<view class="title">
				<text>商品介绍</text>
			</view>
			
			<view class="content">
				<jyf-parser :html="dataInfo.content" ref="article"></jyf-parser>
			</view>
		</view>
		<!-- 底部 -->
		<view class="page-footer">
			<view class="footer-fn" v-if="dataInfo.goods_type!=3">
				<!-- <view class="list">
					<text class="iconfont icon-kefu"></text>
					<text>联系客服</text>
				</view> -->
				<view class="list" @click="onTohome">
					<tui-icon name="shop" :size="22" color="#333"></tui-icon>
					<text>首页</text>
				</view>
				<view class="list" @click="onToCart">
					<text class="iconfont icon-cart"></text>
					<text>购物车</text>
				</view>
			</view>
			<view class="footer-buy" v-if="dataInfo.goods_type!=3&&dataInfo.goods_type!=4">
				<view class="buy-at" style="width: 100%;"  @click="getShow(3)">
					<text>立即购买</text>
				</view>
				<!-- <view class="cart-add"  @click="getShow(2)">
					<text>加入购物车</text>
				</view>
				<view class="buy-at"  @click="getShow(3)">
					<text>立即购买</text>
				</view> -->
			</view>
			<view class="footer-buy" v-if="dataInfo.goods_type==3||dataInfo.goods_type==4" style="width: 100%;margin-left: 4%;">
				<view class="buy-at" style="width: 100%;"  @click="getShow(3)">
					<text>兑换</text>
				</view>
			</view>
		</view>
		<!-- 服务弹窗 -->
		<goods-serve ref="GoodsServe"></goods-serve>
		<!-- 优惠券 -->
		<goods-coupon ref="GoodsCoupon"></goods-coupon>
		<!-- 属性规格 -->
		<view class="cu-modal bottom-modal" :class="{'show':isShow}" @click="hide">
		  <view class="cu-dialog">
				<view class="goods-data">
					<view class="thumb">
						<image :src="data_xuan.goods_image||dataInfo.cover" mode=""></image>
					</view>
					<view class="item">
						<view class="title">
							<text>{{dataInfo.name}}</text>
						</view>
						<view class="price" style="align-items: flex-end;" v-if="dataInfo.goods_type!=3&&dataInfo.goods_type!=4">
							<text class="min">￥</text>
							<text class="max">{{data_xuan.price_selling||dataInfo.price_selling}}<text style="color: #f20;" v-if="dataInfo.balance2!=0">+{{dataInfo.balance2}}<text style="font-size: 24rpx;">礼品卡</text></text></text>
							<view class="" style="margin-left: 10rpx;color: #999;text-decoration: line-through;">{{data_xuan.price_market||dataInfo.price_market}}</view>
						</view>
						<view class="price" v-if="dataInfo.goods_type==3">
							<text class="max">{{data_xuan.price_selling||dataInfo.price_selling}}</text><text style="color: #f20;margin-left: 10rpx;font-weight: 700;">礼品卡</text>
						</view>
						<view class="price" v-if="dataInfo.goods_type==4">
							<text class="max" v-if="data_xuan.price_selling!=0">{{data_xuan.price_selling||dataInfo.price_selling}}+</text><text class="max">{{data_xuan.balance3||dataInfo.balance3}}</text><text style="color: #f20;margin-left: 10rpx;font-weight: 700;">红包券</text>
						</view>
						<!-- <view class="inventory">
							<text v-if="data_xuan">库存：{{data_xuan.stock_total - data_xuan.stock_sales}}</text>
							<text v-else>库存：{{dataInfo.stock_total - dataInfo.stock_sales}}</text>
							<text style="margin-left: 20rpx;">销量：{{data_xuan.stock_sales||dataInfo.stock_sales}}</text>
						</view> -->
					</view>
				</view>
				<view class="attr-size">
					<!-- <view class="attr-list" style="padding-top: 30rpx;">
						<scroll-view scroll-y="true" style="max-height: 550rpx;">
							<view class="size-list">
								<div style="margin-bottom: 20rpx;" class="list" v-for="(item,ins) in datas" :key='ins' :class="item.check?'action':(item.stock_total-item.stock_sales<=0)?'actions':''" @click.stop="tabs_index(item)">
									<text>{{item.goods_spec}}</text>
								</div>
							</view>
						</scroll-view>
					</view> -->
					<view class="attr-list" v-for="(item,index) in dataInfo.specs" :key="index">
						<view class="title">
							<text>{{item.name}}</text>
						</view>
						<view class="size-list">
							<div style="margin-bottom: 20rpx;" class="list" v-for="(ite,ins) in item.list" :key='ins'  v-bind:class="[ite.isShow?'':'noneActive',subIndex[index] == ins?'action':'']"  @click.stop="tabs_index(ite.name,index,ins)">
								<text>{{ite.name}}</text>
							</div>
						</view>
						
					</view>
					<view class="attr-number" @click.stop="onStop">
						<view class="tit">数量</view>
						<view class="number">
							<tui-numberbox  :min="1" :value="value" @change="change"></tui-numberbox>
						</view>
					</view>
				</view>
				<view class="attr-btn">
					<view class="add-cart" v-if="BuyType === 1" @click="addCat()">加入购物车</view>
					<view class="add-buy" v-if="BuyType === 1" @click="submit()">{{dataInfo.goods_type==3||dataInfo.goods_type==4?'兑换':'立即购买'}}</view>
					<view class="confirm" v-if="BuyType === 2 || BuyType === 3" @click="onConfirm(BuyType)">{{dataInfo.goods_type==3||dataInfo.goods_type==4?'兑换':'确定'}}</view>
				</view>
			</view>
		</view>
		<view class="flex flex-align flex-center zhezhao" v-if="isloading">
			<loading></loading>
		</view>
	</view>
</template>

<script>
	import GoodsServe from '../../components/GoodsServe/GoodsServe.vue';
	import GoodsCoupon from '../../components/GoodsCoupon/GoodsCoupon.vue';
	import loading from "@/components/loading/loading.vue"
	import GoEasy from '@/uni_modules/goeasy-js/js_sdk/goeasy-2.12.4.esm.min.js';
	import webUni from "@/common/uni.webview.js"
	export default {
		components: {
			GoodsServe,
			GoodsCoupon,
			loading
		},
		data() {
			return {
				TabShow: 0,
				isMore: false,
				AttentionShow: 0,
				
				web_content: '<div class="m-img"><img src="https://zhedplus.oss-cn-hangzhou.aliyuncs.com/content_img/20191118/1fb5ff162f25fd4c7383bd998ff2fde9.jpg"><div class="tools" hidden><i class="fa fa-arrow-up move-up"></i><i class="fa fa-arrow-down move-down"></i><em class="move-remove" hidden ><i class="fa fa-times" aria-hidden="true"></i> 移除</em><div class="cover"></div></div></div>',
				PageScrollTop: 0,
				type: 0,
				id:'',
				dataInfo:'',
				dataSpecs:'',
				shop_key:'',
				datas:'',
				data_xuan:'',
				value:1,
				goods_comment:[],
				banner:'',
				isShow:false,
				// 购买类型
				BuyType: 0,
				isloading:false,
				order_no:'',
				timer:null,
				goeasy:'',
				isSocket:false,
				work_union:'',
				types:'',
				shopItemInfo:{},
				selectArr: [], 
				showAttr: "",
				subIndex: [],
			};
		},
		onLoad(params) {
			this.id = params.id || 0;
			this.types=params.type?params.type:'0'
		},
		onPageScroll(e) {
			this.PageScrollTop = e.scrollTop;
		},
		onShow() {
			let that = this
			this.getdata()
			uni.$off('getPositonsOrder');
			uni.$off('isSocket');
			uni.$off('isbtn');
			uni.$on('getPositonsOrder', function(data) {
				if(data.order_status=="created"){
					if(that.types==1){
						webUni.navigateTo({
							url: '/pages/ConfirmOrder/ConfirmOrder?order_no='+that.order_no
						})
					}else{
						that.tui.href('/pages/ConfirmOrder/ConfirmOrder?order_no='+that.order_no)
					}
					that.socketIo.Close()
					that.isSocket = false
				}
			});
			uni.$on('isSocket', function(data) {
				that.isSocket = data
			});
			uni.$on('isbtn', function(data) {
				console.log(data)
				that.isloading = !data
			});
			// _get.base()
		},
		// #ifdef MP
		onShareAppMessage() {
			return {
				title:this.dataInfo.name,
				path:'/pages/GoodsDetails/GoodsDetails?inviter_code='+uni.getStorageSync('inviter_code')+"&shopId="+this.id,
			};
		},
		// #endif
		onUnload() {
			let that = this
			that.isloading = false
			/** 这里只保留最新的15条会话记录，以保证初次加载性能 */
			uni.$off('getPositonsOrder');
			uni.$off('isSocket');
			uni.$off('isbtn');
			if(that.isSocket){
				if(that.dataInfo.push_switch==1){
					that.closeGoeasy()
				}else{
					that.socketIo.Close()
				}
			}
		},
		onHide() {
			let that = this
			that.isloading = false
			uni.$off('getPositonsOrder');
			uni.$off('isSocket');
			uni.$off('isbtn');
			if(that.isSocket){
				if(that.dataInfo.push_switch==1){
					that.closeGoeasy()
				}else{
					that.socketIo.Close()
				}
			}
		},
		methods: {
			/**
			 * 返回
			 */
			onBack() {
				let that = this
				uni.switchTab({
					url:'/pages/home/home'
				})
				if(that.dataInfo.push_switch==1){
					that.closeGoeasy()
				}else{
					that.socketIo.Close()
				}
			},
			hide(){
				this.isShow = false;
			},
			onStop(){
				
			},
			getSockt(){
				let that = this
				that.goeasy.connect({
					onSuccess: function () {  //连接成功
					  console.log("GoEasy connect successfully.") //连接成功
					},
					onFailed: function (error) { //连接失败
					  console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
					},
					onProgress:function(attempts) { //连接或自动重连中
					  console.log("GoEasy is connecting", attempts);
					}
				});
				that.goeasy.pubsub.subscribe({
				    channel: that.work_union,//替换为您自己的channel
				    onMessage: function (message) {
				        //收到消息
				        console.log("Channel:" + message.channel + " content:" + message.content);
						if(message.channel==that.work_union){
							that.isloading =false
							that.closeGoeasy()
							if(that.types==1){
								console.log(webUni.getEnv)
								webUni.getEnv(function(res) {
									console.log('当前环境：' + JSON.stringify(res));
								});
								
								webUni.navigateTo({
									url: '/pages/ConfirmOrder/ConfirmOrder?order_no='+message.content
								})
								
							}else{
								that.tui.href('/pages/ConfirmOrder/ConfirmOrder?order_no='+message.content)
							}
							
						}
				    },
				    onSuccess: function () {
				        console.log("Channel订阅成功:"+that.work_union);
						that.isSocket = true
				    },
				    onFailed: function (error) {
				        console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" + error.content)
				    }
				});
			},
			closeGoeasy(){
				let that = this
				this.goeasy.disconnect({
					onSuccess: function(){
						console.log("GoEasy disconnect successfully.")
						that.isSocket = false
					},
					onFailed: function(error){
						console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
					}
				});
			},
			change: function(e) {
				this.value = e.value;
			},
			go_url(e){
				this.tui.href(e)
			},
			getShow(e){
				let that = this
				that.BuyType = e
				that.isShow = true
			},
			tabs_index(item, n, index){
				
				var self = this;
				
				if (self.selectArr[n] != item) {
					self.selectArr[n] = item;
					self.subIndex[n] = index;
				
				} else {
					self.selectArr[n] = undefined;
					self.subIndex[n] = -1; //去掉选中的颜色
					self.data_xuan = ''
				}
				
				var showarr = self.selectArr;
				var tempTop = [];
				showarr.forEach((item, i, arr) => {
					if (item) {
						tempTop.push(item)
					}
				})
				 
				self.showAttr = tempTop.join(";");
				self.getGuige();
				tempTop = []
			},
			getGuige(e){
				var self = this;
				var option = self.dataInfo.specs;
				var result = []; //定义数组存储被选中的值
				option.map((item,index)=>{
					result[index] = self.selectArr[index] ? self.selectArr[index] : '';
				})
				if (self.shopItemInfo[result.join(";")]) {
					self.data_xuan = self.shopItemInfo[result.join(";")]
				}
				for (var i in option) {
					var last = result[i]; //把选中的值存放到字符串last去
					for (var k in option[i].list) {
						result[i] = option[i].list[k].name; //赋值，存在直接覆盖，不存在往里面添加name值
						option[i].list[k].isShow = self.isMay(result); //在数据里面添加字段isShow来判断是否可以选择
					}
					result[i] = last; //还原，目的是记录点下去那个值，避免下一次执行循环时避免被覆盖
				}
				self.$forceUpdate(); //重绘
			},
			isMay: function(result) {
				for (var i in result) {
					if (result[i] == '') {
						return true; //如果数组里有为空的值，那直接返回true
					}
				}
				if (this.shopItemInfo[result.join(";")]) { //匹配选中的数据的库存，若不为空返回true反之返回false
					return (this.shopItemInfo[result.join(";")].stock_total- this.shopItemInfo[result.join(";")].stock_sales)==0 ? false : true;
				}
			},
			getdata(){
				let that = this
				that.tui.request("api.data/getGoods", "POST", {code:that.id}, false, false, true).then((res) => {
					if(res.code==1){
						that.AttentionShow = res.data.is_attention
						that.dataInfo = res.data
						that.banner =res.data.slider
						that.work_union = res.data.work_union
						that.goods_comment = res.data.goods_comment
						that.datas = res.data.items
						for (var i in that.datas) {
							that.shopItemInfo[that.datas[i].filtered_spec] = that.datas[i]; 
						}
						if(res.data.spec_type==1){
							that.data_xuan = res.data
						}
						let data = {}
						data.title = uni.getStorageSync('shareTitle')
						data.desc = res.data.name
						data.share_img = res.data.cover
						uni.setStorageSync('shareShop', data)
						if(res.data.spec_type==2){
							that.getGuige(1)
						}
						that.tui.wxShare(2,this.id)
						that.tui.zhiboList(1)
						
					}
				}).catch((res) => {
					
				})
			},
			onConfirm(e){
				let that = this
				if(e==2){
					this.addCat()
				}else if(e==3&&that.dataInfo.entrance_id==3){
					this.submit1()
				}else if(e==3&&that.dataInfo.entrance_id!=3){
					this.submit()
				}
			},
			submit() {
				let that = this
				if(!that.data_xuan){
					that.tui.toast('商品规格不能为空')
					return
				}
				if(that.data_xuan.stock_total- that.data_xuan.stock_sales<=0||that.value>(that.data_xuan.stock_total- that.data_xuan.stock_sales)){
					that.tui.toast('库存不足')
					return
				}
				that.isShow = false;
				that.isloading = true
				let data = that.dataInfo.code+'@'+that.value
				let datas= {
				  "buy_now_goods_req": {
					"buy_num": that.value,
					"goods_id":that.dataInfo.id,
					"sku_id": that.dataInfo.spec_type==1?0:that.data_xuan.id
				  },
				  "work_union": "string"
				}
				that.tui.addrequest("order/create", "POST", datas, false, false, true).then((res) => {
					if(res.code==0){
						that.isloading = false
						that.order_no = res.data.order_no
						webUni.navigateTo({
							url: '/pages/ConfirmOrder/ConfirmOrder?order_no='+that.order_no
						})
					}else{
						that.tui.toast(res.message)
					}
					
				}).catch((res) => {
					that.submit1()
				})
			},
			submit1() {
				let that = this
				if(that.data_xuan.stock_total- that.data_xuan.stock_sales<=0||that.value>(that.data_xuan.stock_total- that.data_xuan.stock_sales)){
					that.tui.toast('库存不足')
					return
				}
				that.isloading = true
				that.isShow = false;
				let data = that.dataInfo.code+'@'+that.value
				if(that.dataInfo.goods_type==3&&that.dataInfo.entrance_id==3){
					that.tui.request("api.auth.order/exchangeShop", "POST", {items:data,work_union:that.work_union,goods_sku:that.data_xuan.id,type:that.types,coupon_id:that.dataInfo.coupon_id}, false, false, true).then((res) => {
						that.tui.toast(res.info)
						if(res.code==1){
							webUni.navigateTo({
								url: '/pages/MyOrderList/MyOrderList'
							})
						}
					}).catch((res) => {
						
					})
				}else{
					that.tui.request("api.auth.order/add", "POST", {items:data,work_union:that.work_union,goods_sku:that.data_xuan.id,type:that.types}, false, false, true).then((res) => {
						if(res.code==1){
							that.order_no = res.data.order_no
							that.isloading = false
							webUni.navigateTo({
								url: '/pages/ConfirmOrder/ConfirmOrder?order_no='+that.order_no
							})
							return
							if(that.dataInfo.goods_type==2){
								that.isloading = true
								setTimeout(function(){
									if(that.isloading){
										that.getStatus()
									}
								},3000)	
							}else if(that.dataInfo.goods_type==4&&that.types==1){
								that.isloading = true
								setTimeout(function(){
									if(that.isloading){
										that.getStatus()
									}
								},3000)	
							}else{
								webUni.navigateTo({
									url: '/pages/ConfirmOrder/ConfirmOrder?order_no='+that.order_no
								})
							}
							
						}else{
							that.tui.toast(res.info)
						}
					}).catch((res) => {
						
					})
				}
				
			},
			addCat(){
				let that = this
				that.isShow = false;
				let data = that.dataInfo.code+'@'+that.value
				that.tui.request("api.auth.order/addCart", "POST", {items:data}, false, false, false).then((res) => {
					that.tui.toast(res.info)
					if(res.code==1){
						that.getdata()
					}
				}).catch((res) => {
					
				})
			},
			/**
			 * tab
			 */
			onTab(type) {
				this.TabShow = type;
				switch (type) {
					case 0:
						uni.pageScrollTo({
							scrollTop: 0,
							duration: 300
						});
						break;
					case 1:
						uni.createSelectorQuery().select(".evaluate-data").boundingClientRect((data) => { //data - 各种参数
							uni.pageScrollTo({
								scrollTop: this.PageScrollTop + data.top - 50,
								duration: 300
							});
						}).exec()
						break;
					case 2:
						uni.createSelectorQuery().select(".products-introduction").boundingClientRect((
						data) => { //data - 各种参数
							uni.pageScrollTo({
								scrollTop: this.PageScrollTop + data.top - 50,
								duration: 300
							});
						}).exec()
						break;
				}
			},
			/**
			 * 去购物车
			 */
			onToCart() {
				webUni.switchTab({
					url: '/pages/cart/cart'
				})
			},
			onTohome(){
				webUni.switchTab({
					url: '/pages/home/home'
				})
			},

			/**
			 * 关注点击
			 */
			onAttention() {
				let that = this
				that.tui.request("api.auth.order/attention", "POST", {code:that.id,type:that.AttentionShow==1?'2':'1'}, false, false, true).then((res) => {
					that.tui.toast(res.info)
					if(res.code==1){
						that.getdata()
					}
				}).catch((res) => {
					
				})
				

			},
			getStatus() {
				let that = this
				that.tui.request("api.auth.order/orderStatus", "post", {order_no: that.order_no}, false, true, true).then((res) => {
					if (res.code == 1) {
						if(res.data.status==1){
							if(that.dataInfo.push_switch==1){
								that.closeGoeasy()
							}else{
								that.socketIo.Close()
							}
							that.isloading =false
							if(that.types==1){
								webUni.navigateTo({
									url: '/pages/ConfirmOrder/ConfirmOrder?order_no='+that.order_no
								})
								
							}else{
								that.tui.href('/pages/ConfirmOrder/ConfirmOrder?order_no='+that.order_no)
							}
						}
					}
			
				}).catch((res) => {
					console.log(res)
				})
			},
			
		}
	};
</script>

<style scoped lang="scss">
	@import 'GoodsDetails.scss';
	.zhezhao{background: rgba(0, 0, 0, .3);
		position: fixed;top: 0;left: 0;width: 100%;height: 100%;z-index: 11111;
	}
</style>